package org.codeart.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {

    private static int count = 0;
    
    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                // 加锁操作放在 try 块外面 防止获取锁失败执行 finally 块, 没有获取到锁
                // unlock 解锁方法会抛出异常
                lock.lock();
                try {
                    count++;
                } finally {
                    lock.unlock();
                }
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                lock.lock();
                try {
                    count--;
                } finally {
                    lock.unlock();
                }
            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}
